package enterprise.manage.web.filter.beautifyhtml;


import com.opensymphony.module.sitemesh.filter.HttpContentType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * Filter that replaces all occurrences of a given string with a
 * replacement.
 * This is an abstract class: you <I>must</I> override the getTargetString
 * and getReplacementString methods in a subclass.
 * The first of these methods specifies the string in the response
 * that should be replaced. The second of these specifies the string
 * that should replace each occurrence of the target string.
 */
public class BeautifyHtmlFilter implements Filter {
    private static final Log logger = LogFactory.getLog(BeautifyHtmlFilter.class);
    private String defaultEncoding = "utf-8";
    private String contentType = "text/html";
    private Boolean debug = false;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        BeautifyResponseWrapper responseWrapper = new BeautifyResponseWrapper((HttpServletResponse) response);
        // Invoke resource, accumulating output in the wrapper.
        chain.doFilter(request, responseWrapper);
        // Get character array representing output.
        char[] responseChars = responseWrapper.toCharArray();

        Boolean beautifyMatch = false;

        String charsetName = defaultEncoding;
        if (responseWrapper.getContentType() != null) {
            HttpContentType httpContentType = new HttpContentType(responseWrapper.getContentType());
            if (httpContentType.getEncoding() != null) {
                charsetName = httpContentType.getEncoding();
            }

            if (debug) {
                logger.info("响应文档的文档类型是：" + httpContentType.getType());
                logger.info("响应文档的编码类型是：" + httpContentType.getEncoding());
            }

            String url = ((HttpServletRequest) request).getRequestURI();
            url = url == null ? "" : url.replace("\r","\\r").replace("\n","\\n");
            if (httpContentType.getType() != null && httpContentType.getType().length() > 0 && contentType.indexOf(httpContentType.getType()) >= 0) {
                if (debug) {
                    logger.info("请求的uri：" + url + "进入html美化处理过程...");
                }
                beautifyMatch = true;
                responseChars = beautify(responseChars);
            }
        }

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteStream, charsetName);
        outputStreamWriter.write(responseChars);
        outputStreamWriter.close();

        if (beautifyMatch) {
            // Update the Content-Length header.
            if (debug) {
                logger.debug("设置contentLength：" + byteStream.size());
            }
            response.setContentLength(byteStream.size());
        }

        OutputStream outputStream = response.getOutputStream();
        byteStream.writeTo(outputStream);
    }

    /**
     * 　　 * Store the FilterConfig object in case subclasses want it.
     */
    public void init(FilterConfig filterConfig) throws ServletException {

        if (filterConfig.getInitParameter("encoding") != null && filterConfig.getInitParameter("encoding").length() > 0) {
            defaultEncoding = filterConfig.getInitParameter("encoding");
            if (debug) {
                logger.info("设置html美化过滤器默认编码类型是：" + defaultEncoding);
            }
        }

        if (filterConfig.getInitParameter("contentType") != null && filterConfig.getInitParameter("contentType").length() > 0) {
            contentType = filterConfig.getInitParameter("contentType");
            if (debug) {
                logger.info("设置html美化过滤器支持的文档类型是：" + contentType);
            }
        }

        if (filterConfig.getInitParameter("debug") != null && filterConfig.getInitParameter("debug").length() > 0) {
            debug = "true".equalsIgnoreCase(filterConfig.getInitParameter("debug"));
            if (debug) {
                logger.info("设置html美化过滤器调试开关是否打开：" + debug);
            }
        }
    }

    public void destroy() {
    }

    /**
     * 传入原始的字符数组，替换空行，删除多余空格后返回新的字符数组
     *
     * @param responseChars 响应的数据字符数组
     * @return 处理后的字符数组
     */
    private char[] beautify(char[] responseChars) {
        long startTime = System.currentTimeMillis();
        final char CHAR_SPACER = 32;

        //begin
        StringBuffer htmlBuffer = new StringBuffer(responseChars.length);

        StringBuffer lineBuffer = new StringBuffer();
        char lastChar = 0;
        for (char c : responseChars) {
            if (lastChar < CHAR_SPACER && c <= CHAR_SPACER) {
                //如果前一个字符是换行，当前字符是换行或者空格，都不处理，仅仅记录
                lastChar = 0;
                htmlBuffer.append(lineBuffer);
                lineBuffer = new StringBuffer();
            } else if (c == CHAR_SPACER && lastChar == CHAR_SPACER) {
                //当前字符是空格，而前一个字符也是“ ”，不处理
                lastChar = c;
            } else {
                //其他字符，进入行缓冲
                lineBuffer.append(c);
                lastChar = c;
            }

        }
        htmlBuffer.append(lineBuffer);
        long endTime = System.currentTimeMillis();
        long wasteTime = endTime - startTime;
        if (debug) {
            logger.info("html美化耗时：" + wasteTime);
        }
        return htmlBuffer.toString().toCharArray();
    }
}

